/**
 * 
 */
package com.iknight.mgr.core.tree;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Jeryzym
 *
 */
public class TreeUtils {
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static synchronized <T extends TreeNode> List<T> getRootNode(List<T> treeNodes) {
		List<T> newTreeNodes = new ArrayList<T>();
		for (T node : treeNodes) {
			if (null == node.getPid() || node.getPid().equals("")) {
				node.setNodes(getChildNodes(node.getId(), treeNodes));
				newTreeNodes.add(node);
			}
		}
		return newTreeNodes;
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static final <T extends TreeNode> List<T> getChildNodes(String parentId, List<T> treeNodes) {
		List<T> childNodes = new ArrayList<T>();
		for (T node : treeNodes) {
			if (null != node.getPid() && !node.getPid().equals("")) {
				if (node.getPid().equals(parentId)) {
					node.setNodes(getChildNodes(node.getId(), treeNodes));
					childNodes.add(node);
				}
			}
		}
		return childNodes;
	}
}
